setInterval("reloadIfNeeded()", 1000);

// Add listener for when the page is unloaded
// You have 4 seconds from hearing this event to 
// the pop-up page being disposed
pokki.addEventListener('popup_unload', onUnload);
pokki.addEventListener('context_menu', function(menu_item){
  logout();
});

function onUnload() {
    // Time to save any state
}

// Add listener for when the page is loaded
window.addEventListener('load', onLoad, false);

function onLoad() {

    // Perform pop-up page initiation and configuration
    // Time to restore any state
    localStorage.setItem("first_time","yeah");
    renderLogin();
    applyListeners();
    if(!nullOrEmpty(user) && !nullOrEmpty(password))
      doLogin(user, password);

}

// Add listener for when the pop-up window is shown
pokki.addEventListener('popup_shown', onShow);

function onShow() {
    reloadIfNeeded();
}

// Add listener for when the pop-up window is hidden
pokki.addEventListener('popup_hidden', onHide);

function onHide() {
}

function login(user, password) {
    user = $("#user").val();
    password = $("#password").val();

    if(!nullOrEmpty(user) && !nullOrEmpty(password))
      doLogin(user, password);
}

function logout() {
    localStorage.removeItem("password");
    localStorage.removeItem("cookie");
    renderLogin();
    pokki.removeIconBadge();
    pokki.resetContextMenu();
}

function renderLogin() {
    user = localStorage.getItem("user");
    password = getPassword();

    $("#template_content").html($("#login_template").tmpl({user: user, password: password}));
    $("body").removeClass("messages");
    $('.tooltip').tipsy({gravity: 'se', fade: true});
    removePreloader();
}

function renderMessages(messages) {
    removePreloader();
    $("#template_content").html($("#messages_template").tmpl({messages: messages["message_list"], after: messages["after"] }));
    // Scroll jquery
    $("body").addClass("messages");
    $('.scroll-pane').jScrollPane();
    $('.tooltip').tipsy({gravity: 'se', fade: true});
}

function loadMessages(errors) {
    $.get(inbox_url, function(data) {
        renderMessages(parseMessagesJSON(data));
        removePreloader();
    });
}
function parsePostsJSON(data){
    posts = {};
    posts["post_list"] = []
    if(data.data){
        $.each(data.data.children, function(index,value){
            score = value.data.score;
            title = value.data.title;
            user = value.data.author;
            subreddit = value.data.subreddit;
            time_ago = time_ago_in_words(value.data.created_utc);
            num_comments = value.data.num_comments;
            permalink = value.data.permalink;
            url = value.data.url;
            posts["post_list"].push({score: score,
                        title: title,
                        user: user,
                        subreddit: subreddit,
                        time_ago: time_ago,
                        num_comments: num_comments,
                        permalink: permalink,
                        url: url
            });
        });
      posts["after"] = data.data.after;
    }
    return posts;
}
function parseMessagesJSON(data) {
  messages = {};
  messages["message_list"] = [];
  if(data.data){
    messages["after"] = data.data.after;

      $.each(data.data.children, function(index, value) {
        author = value.data.author;
        body = value.data.body;
        class_message_type = "";
        vic = value.data.context;
        posted_time_ago = time_ago_in_words(value.data.created_utc);
        thing_id = value.data.name;
        if (value.data.new)
        {
          class_message_type = (value.data.context == "") ? "pm-unread" : "pr-unread";
        }
        else
        {
          class_message_type = (value.data.context == "") ? "pm" : "pr";
        }
        messages["message_list"].push({
          author: author,
          body: body,
          class_message_type: class_message_type,
          view_in_context: vic,
          posted_time_ago: posted_time_ago,
          thing_id: thing_id
        });
      });
  }

  return messages;
}

function doLogin(user, password) {
    showPreloader();
    $("#error").remove();
    $.post(login_url + "/" + user, {user: user, passwd: password, api_type: "json"}, function(data) {
        if (data.json.errors.length == 0) {
            pokki.addContextMenuItem("Logout from reddit", "logout_menu");
            $.cookie("reddit_session", data.json.data.cookie);
            saveCookie(data.json.data.cookie);
            localStorage.setItem("user", user);
            savePassword(password);
            saveModHash(data.json.data.modhash)
            loadMessages();
            updateBadgeFirstTime();
        }
        else {
            removePreloader();
            if(data.json.errors.length>0){
              if(data.json.errors[0][1]){
                showError(data.json.errors[0][1]);
              }
            }
        }

    }).error(function(){
       showError("HTTP error")
    });
}

function reloadIfNeeded() {
    if (!nullOrEmpty(localStorage.getItem("need_to_refresh"))){
        localStorage.removeItem("need_to_refresh");
        loadMessages();
    }
}

function time_ago_in_words(epoch_time) {
  diff_in_seconds = Math.round((new Date() - new Date(epoch_time * 1000)) / 1000);

  matrix = [
    [60, null, "just now"],
    [3600, 60, "minutes ago"],
    [7200, 3600, "hours ago"],
    [172800, null, "yesterday"],
    [604800, 86400, "days ago"],
    [1209600, null, "last week"],
    [2419200, 604800, "weeks ago"],
    [4838400, null, "last month"],
    [29030400, 2419200, "months ago"],
    [58060800, null, "last year"],
    [2903040000, 29030400, "years ago"]
  ];

  i = 0;
  while (diff_in_seconds >= matrix[i][0]) {
    i++;
  }

  if (matrix[i][1] != null) {
    return Math.round(diff_in_seconds / matrix[i][1]) + " " + matrix[i][2];
  }
  else {
    return matrix[i][2];
  }
}

function applyListeners() {

  $(".orange-button").live("click", function(e) {
    e.stopPropagation();
    e.preventDefault();
    login();
  });

  $(".external_link").live("click",function(){
    pokki.openURLInDefaultBrowser($(this).attr("href"));
    pokki.closePopup();
  });

  $(".time").live("click", function(e) {
    e.stopPropagation();
  });

  $(".context").live("click", function(e) {
    pokki.openURLInDefaultBrowser('http://www.reddit.com' + $(this).attr("href"));
    pokki.closePopup();
    e.stopPropagation();
  });

  $(".reply").live("click", function(e) {
    addReplyFields($(this));
    $('.scroll-pane').jScrollPane();
    e.stopPropagation();
  });

  $("#logout").live("click", function() {
    logout();
  });

  $("#user").live("keypress", function(e) {
    if (e.which == 13) {
      login();
    }
  });

  $("#password").live("keypress", function(e) {
    if (e.which == 13) {
      login();
    }
  });

  $(".btn_comment").live("click",function(e){
    sendComment($(this));
  });

  $(".show-more").live("click", function() {
    after = $(this).attr("after");
    $(this).addClass("loading");

    messages = [];

    $.get(inbox_url + "?after=" + after, function(data) {
      $(".show-more").remove();
      messages = parseMessagesJSON(data);
      $("#messages_list").append($("#message_list_template").tmpl({after: messages.after, messages: messages.message_list}));
      $('.scroll-pane').jScrollPane();
      $('.tooltip').tipsy({gravity: 'se', fade: true});
    });
  });

  $(".show-more-posts").live("click", function() {
    after = $(this).attr("after");
    $(this).addClass("loading");

    posts = [];

    $.get(posts_url + "?after=" + after, function(data) {
      $(".show-more-posts").remove();
      posts = parsePostsJSON(data);
      $("#post_list").append($("#post_list_template").tmpl({after: posts.after, posts: posts.post_list}));
      $('.scroll-pane').jScrollPane();
    });
  });

  $("#whatshot-tab").live("click",function(){
      $("#tabs ul li").removeClass("selected-tab");
      $("#whatshot-tab").addClass("selected-tab");

      showPreloader();
      loadPosts();
  });
  $("#messages-tab").live("click",function(){
      $("#tabs ul li").removeClass("selected-tab");
      $("#messages-tab").addClass("selected-tab");

      showPreloader();
      loadMessages();

  });
}
function showPreloader(){
  $("#template_content").append($("<div id='preloader'><img src='img/preloader.gif'></div>"));
}
function removePreloader(){
  $("#preloader").remove();
}
function showError(error_msg){
 $("#template_content").append($("<div id='error'><p></p></div>"));
 $("#error p").text(error_msg);
 $("#error").delay(4000);
 $("#error").fadeOut("fast");
}

function addReplyFields(elem) {
    msg_div = elem.parent().parent();
    if (msg_div.children().last().hasClass("reply_p")) {
        msg_div.children().last().remove();
    }
    else {
        $(".reply_p").remove();
        msg_div.append("<p class='reply_p'></p>");
        $(".reply_p").append("<textarea></textarea>");
        $(".reply_p").append("<button class='btn_comment'>send</button>");
        $("textarea").focus();

    }

}
function sendComment(elem){
    text = $(elem.siblings()[0]).val();
    if(text!=""){
        thing_id = elem.parent().parent().attr("thing-id");
        h={parent: thing_id, uh: getModHash(),text: text};
        $.post("http://www.reddit.com/api/comment",h, function(data){
        });
    }
    $(".reply_p").remove();
    $('.scroll-pane').jScrollPane();
}

function loadPosts(){
    $.get(posts_url, function(data) {
        posts = parsePostsJSON(data);
        $("#template_content").html($("#whatshot_template").tmpl({posts: posts.post_list , after: posts.after}));
        $('.scroll-pane').jScrollPane();
        removePreloader();
    });

}

function updateBadgeFirstTime(){
  $.get(unread_msg_url,function(data){
			if(data!=""){
        unread_count = data.data.children.length;
        if(unread_count == 0){
          pokki.removeIconBadge();
        }
        else{
          console.log("set icon pop");
          pokki.setIconBadge(unread_count);
        }
			}
		});
}
